package org.iryshka.skyserver;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class HTTPRequestHandler {

	public static File defaultPage = new File("C:/inetpub/wwwroot/SkyNetwork_welcome.html"); // CONFIG data

	public static File serverDir = new File(ConfigAnalyzer.getServerDirectory()); // CONFIG data
	public static String requestResDir;// full path to file
	public static String fileLocationDir;

	public String hashMapAnalyze(String extension) {
		String str = ContentTypeMap.contentTypeMap.get(extension);
		return str == null ? "application/octet-stream" : str;
	}

	private String getFileExtension(String resourceName) {
		if (resourceName.contains(".")) {
			return resourceName.substring(resourceName.lastIndexOf(".") + 1);
		}
		return "html";
	}

	private String URLEscapeReplace(String resourceStr) {
		return resourceStr.replace("%25", "%").replace("%3C", "<").replace("%3E", ">").replace("%23", "#")
				.replace("%20", " ").replace("%7B", "{").replace("%7D", "}").replace("%7C", "|")
				.replace("%5C", "\\").replace("%5E", "^").replace("%7E", "~").replace("%5B", "[")
				.replace("%5D", "]").replace("%60", "`").replace("%3B", ";").replace("%2F", "/")
				.replace("%3F", "?").replace("%3A", ":").replace("%40", "@").replace("%3D", "=")
				.replace("%26", "&").replace("%24", "$");
	}

	HTTPResponse processHttpRequest(HTTPRequest request) throws IOException {
		HTTPResponse response = new HTTPResponse();
		response.setHeaderInMap("Connection:", "close");
		
		String htmlPage = null;
		String resourceName = URLEscapeReplace (request.getResourceName());
		
		String method = request.getRequestMethod();
		if (method.equals("GET")) {
			File resource = null;
			if (resourceName.equals("/")) {
				resource = defaultPage;
			} else {
				resource = new File (serverDir + resourceName);
			}
			
			if (resource == null || !resource.exists()) {
				response.setStatus("404");
				htmlPage = HTMLBuilder.getErrorHtml("404");
			} else if (resource.isFile()) {
				response.setHeaderInMap("Content-length:", Long.toString(resource.length()));
				response.setHeaderInMap("Content-type:", hashMapAnalyze(getFileExtension(resource.getName())));
				response.setResourceStream(new FileInputStream(resource));
			} else if (resource.isDirectory()) {
				if (!ConfigAnalyzer.isListingEnabled()) {
					response.setStatus("403");
					htmlPage = HTMLBuilder.getErrorHtml("403");
				} else {
					htmlPage = HTMLBuilder.formHtmlList (resource, ConfigAnalyzer.getServerDirectory());
				}
			}
		} else if (method.equals("POST") || method.equals("HEAD") || method.equals("DELETE")) {
			htmlPage = HTMLBuilder.getErrorHtml("403");
		}
		
		if (htmlPage != null) {
			response.setHeaderInMap("Content-length:", Integer.toString(htmlPage.length()));
			response.setHeaderInMap("Content-type:", "text/html; charset=utf-8");
			response.setResourceStream(new ByteArrayInputStream(htmlPage.getBytes()));
		}
		return response;
	}
}
